﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SAKS.ViewModels;
using SAKS.Models;
using SAKS.IServices;
using NHibernate;
using SAKS.ActionFilters;

namespace SAKS.Controllers
{
    [Authorize]
    [NeedsPersistence]
    public class AchievementController : ControllerBase
    {
        public IAchievementServices AchievementServices { get; set; }
        public IDocumentServices DocumentServices { get; set; }
        public ISearchServices SearchServices { get; set; }
        public IAwardServices AwardServices {get;set;}

        protected override void Initialize(System.Web.Routing.RequestContext requestContext)
        {
            base.Initialize(requestContext);
            var session = GetCurrentSession(requestContext);
            AchievementServices.Session = session;
            DocumentServices.Session = session;
            SearchServices.Session = session;
            AwardServices.Session = session;
        }

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Create()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Create(AchiViewModel model)
        {
            var achi = AchiMapper.ToAchievement(model);
            var evaluation = AchiMapper.ToEvaluation(model);
            achi.Evaluation = evaluation;
            evaluation.Achievement = achi;
            achi.CreatedDate = DateTime.Now;
            AchievementServices.Save(achi);
            return RedirectToAction("Index");
        }

        public ActionResult List(DataTableParameter param)
        {
            int? _start = param.iDisplayStart;
            int? _pageSize = param.iDisplayLength;
            int first = _start ?? 0;
            int pageSize = _pageSize ?? 20;
            int? totalRecords = new int?();
            var ret = AchievementServices.List(first, pageSize, out totalRecords, param.sSearch);
            var json = Json(
                new dataTableJson
                {
                    sEcho = param.sEcho,
                    iTotalRecords = totalRecords,
                    iTotalDisplayRecords = totalRecords,
                    aaData = ret
                },
                JsonRequestBehavior.AllowGet
            );
            return json;
        }

        public ActionResult Details(Guid id)
        {
            Init(id);
            if (id != null)
            { 
                var model = AchievementServices.Get(id);
                if (model != null)
                {
                    var viewmodel = AchiMapper.ToViewModel(model);
                    ViewBag.AchievementId = viewmodel.Id;
                    return View(viewmodel);
                }
            }
            return HttpNotFound();
        }

        public ActionResult Edit(Guid id)
        {
            Init(id);
            if (id != null)
            {
                var model = AchievementServices.Get(id);
                if (model != null)
                {
                    var viewmodel = AchiMapper.ToViewModel(model);
                    ViewBag.AchievementId = viewmodel.Id;
                    return View(viewmodel);
                }
            }
            return HttpNotFound();
        }
        [HttpPost]
        public ActionResult Edit(AchiViewModel model)
        {
            Init(model.Id);
            if (ModelState.IsValid)
            {
                var achi = AchiMapper.ToAchievement(model);
                var eva = AchiMapper.ToEvaluation(model);
                achi.Evaluation = eva;
                AchievementServices.Update(achi);
                return RedirectToAction("Index");
            }
            else
                return View(model);
        }
        public ActionResult DocumentList(Guid id, int? page, string key)
        {
            Init(id);
            int pageSize = 20;
            int _page = page == null ? 0 : (int)page;
            int start = pageSize * _page;
            int? totalRecords;
            IEnumerable<DocumentInfo> list;
            if (string.IsNullOrEmpty(key))
            {
                list = DocumentServices.GetAchiDocInfoList(id, start, pageSize, out totalRecords);
            }
            else
            {
                list = SearchServices.AchiDocSearch(id, start, pageSize, out totalRecords, key);
                ViewBag.Key = key;
            }

            int totalPages = (int)Math.Ceiling((double)totalRecords / (double)pageSize);
            ViewBag.NextPage = totalPages - 1 > _page ? _page + 1 : -1;
            ViewBag.PrePage = 0 < _page ? _page - 1 : -1;
            ViewBag.UploadAction = "UploadDoc";
            ViewBag.Key = key;
            return View(list);
        }
        public ActionResult UploadDoc(Guid id)
        {
            Init(id);
            return View(new DocumentCreateUpdateModel());
        }
        [HttpPost]
        public ActionResult UploadDoc(DocumentCreateUpdateModel model)
        {
            var id = (Guid)model.AchievementId;
            Init(id);
            if (ModelState.IsValid)
            {

                HttpPostedFileBase doc = Request.Files["doc"];
                var dotindex = doc.FileName.LastIndexOf('.');
                var i = doc.FileName.LastIndexOf('/');
                var j = doc.FileName.LastIndexOf('\\');
                var sindex = i > j ? i + 1 : j + 1;
                var doctype = doc.FileName.Substring(dotindex, doc.FileName.Length - dotindex);
                var docname = doc.FileName.Substring(sindex, doc.FileName.Length - sindex);
                byte[] buf = new byte[doc.ContentLength];
                doc.InputStream.Read(buf, 0, doc.ContentLength);
                var docfile = new DocFile() { Doc = buf, Type = doctype, AchievementId = id, Name = docname };
                var info = DocumentMapper.ToDocumentInfo(model);
                info.DocFile = docfile;
                docfile.DocumentInfo = info;
                info.CreatedDate = DateTime.Now;
                info.Name = docname;
                var fileId = DocumentServices.SaveFile(docfile);
                info.FileId = fileId;
                DocumentServices.SaveInfo(info);
                return RedirectToAction("DocumentList", new { Id = model.AchievementId });
            }
            else
                return View(model);
        }

        public ActionResult Award(Guid id)
        {
            Init(id);
            var list = AchievementServices.GetAwards(id);
            return View(list);
        }
        public ActionResult AddAward(Guid id)
        {
            Init(id);
            return View();
        }

        [HttpPost]
        public ActionResult AddAward(Guid id,Award award)
        {
            Init(id);
            AchievementServices.AddAward(id, award);
            return RedirectToAction("Award", new { Id = id });
        }

        [HttpPost]
        public ActionResult RemoveAward(Guid achiId,Guid awardId)
        {
            AchievementServices.RemoveAward(achiId, awardId);
            return Json(new { AwardId = awardId });
        }


        private void Init(Guid id)
        {
            ViewBag.AchievementId = id;
        }
    }
}
